package datasourse

import (
	"baokaobang/conf"
	"baokaobang/models"
	"fmt"
	"github.com/go-xorm/xorm"
	"github.com/kataras/iris/v12"
	"sync"
)

var (
	masterEngine *xorm.Engine
	mu           sync.Mutex
)

func NewMasterOrm() (*xorm.Engine, error) {
	if masterEngine != nil {
		return masterEngine, nil
	}

	mu.Lock()
	defer mu.Unlock()

	if masterEngine != nil {
		return masterEngine, nil
	}

	var err error

	dataSourceName := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4", conf.MasterDbConfig.User,
		conf.MasterDbConfig.Pwd, conf.MasterDbConfig.Host, conf.MasterDbConfig.Port, conf.MasterDbConfig.DbName)
	masterEngine, err = xorm.NewEngine(conf.DbDriverName, dataSourceName)
	//masterEngine.TZLocation, _ = time.LoadLocation("Asia/Shanghai")
	//masterEngine.ShowSQL(true)

	if err != nil {
		return nil, err
	}

	iris.RegisterOnInterrupt(func() {
		masterEngine.Close()
	})

	err = masterEngine.Sync2(
		new(models.User),
		new(models.UserLabel),
		new(models.University),
		new(models.UniversityLabel),
		new(models.EnrollmentPlan),
		new(models.Major),
		new(models.MajorCategory),
		new(models.Admin),
		new(models.AuthorityCategory),
		new(models.Authority),
		new(models.Role),
		new(models.RoleAuthority),
		new(models.Rank),
		new(models.AdmissionData),
		new(models.Region),
		new(models.Enrollment),
		new(models.Verify),
		new(models.MatchCollege),
		new(models.MatchTeacher),
		new(models.SiteConfig),
		new(models.StudentScore),
		new(models.Feedback),
		new(models.Category),
		new(models.Article),
		new(models.Transaction),
		new(models.College),
		new(models.CollegeLabel),
		new(models.CollegeLevel),
		new(models.Volunteer),
		new(models.HighSchool),
		new(models.HighSchoolClass),
		new(models.Trends),
		new(models.Comment),
		new(models.ThumbsUp),
		new(models.CollegeEnrollment),
		new(models.EnrollProfile),
		new(models.StudentMajorProbability),
		new(models.Label),
		new(models.Invite),
		new(models.Order),
		new(models.CollectionCollege),
		new(models.CollectionMajor),
	)
	if err != nil {
		return nil, err
	}

	return masterEngine, nil
}
